package com.alan.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * 使用NIO完成网络编程的三个核心
 *  1.通道
 *  2.缓冲区
 *  3.选择器
 * Created by Alan on 2017/8/5.
 */
public class Client {

    public static void main(String[] args) throws IOException {
        //获取通道
        SocketChannel channel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));
        //切换到非阻塞模式
        channel.configureBlocking(false);
        //指定缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //发送数据给服务端
        Scanner in = new Scanner(System.in);
        //循环发送
        while (in.hasNext()){
            String info = in.nextLine();
            buffer.put(info.getBytes());
            buffer.flip();
            channel.write(buffer);
            buffer.clear();
        }
        //关闭通道
        channel.close();
    }

}
